package renzheng;

import java.io.*;
import java.net.*;
import java.security.*;
import java.security.cert.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class SecureServer {

    // 客户端和服务器共享的密钥库存放路径和密码
    private static final String KEYSTORE_PATH = "keystore.jks";
    private static final String KEYSTORE_PASSWORD = "zhaoleipeng123";

    // 客户端和服务器共享的密钥别名和密码
    private static final String KEY_ALIAS = "key_alias";
    private static final String KEY_PASSWORD = "zhaoleipeng123";

    // 加密算法
    private static final String ENCRYPTION_ALGORITHM = "RSA";

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(12345);
            System.out.println("Server started. Waiting for client...");

            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println("Client connected.");

                // 服务器接收数据前获取客户端的证书进行验证
                InputStream inputStream = socket.getInputStream();
                // 可以进行一些验证

                // 服务器接收数据的示例
                Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM);
                cipher.init(Cipher.DECRYPT_MODE, getPrivateKey());
                CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
                BufferedReader reader = new BufferedReader(new InputStreamReader(cipherInputStream));
                String message = reader.readLine();
                System.out.println("Client sent: " + message);

                // 服务器发送数据的示例
                OutputStream outputStream = socket.getOutputStream();
                outputStream.write("Hello from server!".getBytes());

                socket.close();
                System.out.println("Client disconnected.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取私钥
    private static PrivateKey getPrivateKey() throws Exception {
        KeyStore keystore = KeyStore.getInstance("JKS");
        FileInputStream fis = new FileInputStream(KEYSTORE_PATH);
        keystore.load(fis, KEYSTORE_PASSWORD.toCharArray());
        fis.close();
        return (PrivateKey) keystore.getKey(KEY_ALIAS, KEY_PASSWORD.toCharArray());
    }
}
